/**
 * $Id: SubmitStatusThread.java,v 1.23 2006/08/30 00:52:15 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.process;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.Queue;
import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.runner.AbsOutQueue;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.smscommand.SubmitCmd;
import com.haoxi.gateway.runner.smscommand.SubmitStatusCmd;
import com.haoxi.gateway.util.db.DBConnectUtil;
import com.haoxi.gateway.util.db.DealOracleDBUtil;

/**
 * 处理submitstatus
 * 
 * Revision History
 * 
 * 2006-5-29,star.Zhao,created it
 */
public class SubmitStatusThread extends AbsOutQueue {
    private static final Log log = LogFactory.getLog(SubmitStatusThread.class);
    private Map submitStatusMap = null;
    private static final String MY_NAME = "SubmitStatusThread";
    private static Vector tmpList;

    public SubmitStatusThread(Queue inQueue, Map mtRespMap) {
        super(inQueue);
        submitStatusMap = mtRespMap;
        setName(MY_NAME);

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.common.AbsOutQueue#doJob(java.lang.Object, int)
     */
    public int doJob(Object pObject, int queueLen) {

        if (null == tmpList) {
            tmpList = new Vector();
        }
        int nRet = AbsOutQueue.PROC_ERROR;
        Map systemConf = RunnerMgr.getInstance().getSystemConf();
        String gateway_history = (String) systemConf
                .get(SYSConst.CONF_DB_HISTORY);
        String gateway_DBName = (String) systemConf.get(SYSConst.CONF_DB_MYSQL);
        if (pObject instanceof SubmitStatusCmd) {
            SubmitStatusCmd submitStatus = (SubmitStatusCmd) pObject;
            
            SubmitCmd submitCmd = null;
            synchronized (submitStatus) {
                submitCmd = (SubmitCmd) submitStatusMap.remove(submitStatus
                        .getSequence());
            }
            log.info("Deal Status submitStatus Sequence=="+ submitStatus.getSequence()  );
            if (null == submitCmd) {
                log.error("have unkown submit response message !!!!!! SequenceID :["
                                + submitStatus.getSequence() + "]");
                nRet = AbsOutQueue.PROC_ERROR;
            } else {

                // deal the status and need report Data
                submitCmd.setMsgId(submitStatus.getMsgID());
                submitCmd.setSubmitStatus(submitStatus.getStatus());

                // persist report Data and delete persistent status
                dealStatusAndReportTempData(submitStatus.getSequence(),
                        submitCmd, gateway_DBName);
                tmpList.add(submitCmd);
                if (tmpList.size() >= GetMTThread.mtListLen) {
                    int[] res = DealOracleDBUtil.saveBatchMsgHistory(MY_NAME,
                            tmpList, gateway_history);
                    log.debug("Submit MT count :[" + GetMTThread.mtListLen
                            + "]");
                    log
                            .info("-----------save Batch submitStatus successfuly, count[: "
                                    + res.length + "]");

                    tmpList.clear();
                    nRet = AbsOutQueue.PROC_NORMAL;
                } 
            }

        }
        return nRet;
    }
    /**
     * delete persist Need status Data and persist Need report Data
     * 
     * @param cmd
     */
    private void dealStatusAndReportTempData(String sequenceId, SubmitCmd cmd,
            String dbName) {
        Connection conn = null;
        PreparedStatement psForStatus = null;
        PreparedStatement psForReport = null;
        // 处理Status数据
        try {
            conn = DBConnectUtil.open(dbName);
            psForStatus = conn
                    .prepareStatement(SQLConst.DELETE_NEED_SUBMITSTATUS_MTDATA);
            psForStatus.setString(1, sequenceId);
            if (1 != psForStatus.executeUpdate()) {
                log
                        .error("Syncronize for delete MT status data into MYsql DB Failed, MT's sequence: ["
                                + sequenceId + "]");
            }

        } catch (SQLException e) {
            log.error("Syncronize for delete MT status data SQLException: ["
                    + e + "]");
            log
                    .error("Syncronize for delete MT status data into MYsql DB Failed, MT's sequence: ["
                            + sequenceId + "]");
        }

        // 处理report数据
        try {

            psForReport = conn
                    .prepareStatement(SQLConst.SAVE_NEED_REPORT_MTDATA);
            psForReport.setString(1, cmd.getMsgId());
            psForReport.setString(2, cmd.getSubmitStatus());
            psForReport.setString(3, sequenceId); // 存放MTSequece
            psForReport.setInt(4, cmd.getStype());
            psForReport.setString(5, cmd.getServiceId());
            psForReport.setString(6, cmd.getOrgMobile());
            psForReport.setInt(7, cmd.getOrgMobileType());
            psForReport.setString(8, cmd.getDestMobile());
            psForReport.setInt(9, cmd.getDestMobileType());
            psForReport.setString(10, cmd.getFeeMobile());
            psForReport.setInt(11, cmd.getFeeMobileType());
            psForReport.setString(12, cmd.getFeeType());
            psForReport.setInt(13, cmd.getFeeCode());
            psForReport.setString(14, cmd.getMsgContent());
            psForReport.setInt(15, cmd.getProvice());
            psForReport.setInt(16, cmd.getCity());
            psForReport.setString(17, cmd.getCityName());
            psForReport.setString(18, cmd.getLinkID());
            psForReport.setInt(19, cmd.getCp());
            psForReport.setString(20, cmd.getSubmitTime());
            psForReport.setString(21, cmd.getGateWayCode());
            psForReport.setString(22, cmd.getSid());
            psForReport.setString(23, cmd.getMomtRelateID());
            if (1 != psForReport.executeUpdate()) {
                log
                        .error("Syncronize for add MT report data into MYsql DB Failed, MT's msgId: ["
                                + cmd.getMsgId() + "]");
            }
            // log.warn("-----------dealStatusAndReportTempData Sequence:
            // "+sequenceId+"--------------");
        } catch (SQLException e) {
            log.error("Syncronize for add MT report data SQLException: [" + e
                    + "]");
            log
                    .error("Syncronize for add MT report data into MYsql DB Failed, MT's msgId: ["
                            + cmd.getMsgId() + "]");
        } finally {
            try {
                if (psForStatus != null) {
                    psForStatus.close();
                }

                if (psForReport != null) {
                    psForReport.close();
                }

                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                log.error("close:", e);
            }
        }
    }

    public static void main(String[] args) {
        int count = (int) (100 / 16);
        System.out.println(count);
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis());
    }

}
